// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Author: wsfuyibing <682805@qq.com>
// Date: 2024-12-05

package message

import (
	"encoding/json"
	"gitee.com/gomq/sr/errs"
	"sync"
)

var (
	notificationPool = sync.Pool{New: func() interface{} {
		return &Notification{}
	}}
)

type Notification struct {
	ResponseBody   []byte `json:"ResponseBody,omitempty"`
	SubscriptionId int    `json:"SubscriptionId,omitempty"`
}

func NewNotification() *Notification { return notificationPool.Get().(*Notification) }

func (o *Notification) Byte() []byte {
	if buf, err := json.Marshal(o); err == nil {
		return buf
	}
	return nil
}

func (o *Notification) Release() { o.releaser() }

func (o *Notification) String() string {
	if buf := o.Byte(); buf != nil {
		return string(buf)
	}
	return "{}"
}

func (o *Notification) Unmarshal(data []byte) (err error) {
	if json.Unmarshal(data, o) != nil {
		err = errs.ErrNotificationBodyNotJsonFormat
		return
	}
	if o.SubscriptionId < 1 || o.ResponseBody == nil {
		err = errs.ErrNotificationBodyNotUnmarshalled
	}
	return
}

// + Access

func (o *Notification) releaser() {
	o.ResponseBody = nil
	o.SubscriptionId = 0
	notificationPool.Put(o)
}
